﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using DBMan.Common.Global;
using DBMan.Common.Helper;
using DBMan.Common.Helper.Udp;

namespace DBMan
{
    public partial class Deal
    {
        /// <summary>
        /// 是否启用Udp广播发送数据
        /// </summary>
        private bool IsUdpPublish = false;
        /// <summary>
        /// Udp广播端口
        /// </summary>
        private int UdpPort = 0;

        /// <summary>
        /// Udp广播发送数据时是否打印日志
        /// </summary>
        private bool IsUdpPublishLog = false;

        /// <summary>
        /// (第二)构造方法
        /// </summary>
        private void DealConstructMethod()
        {
            try
            {
                this.IsUdpPublish = (Configs.GetAndAdd("IsUdpPublish", "True").Trim().ToLower() == "true");
                if (this.IsUdpPublish && int.TryParse(Configs.GetAndAdd("DataPublish_UdpPort", "9895"), out var i))
                {
                    this.UdpPort = i;
                }
                this.IsUdpPublishLog = (Configs.GetAndAdd("IsUdpPublishLog", "True").Trim().ToLower() == "true");
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Deal DealConstructMethod Err:{ex.Message}");
            }
        }

        private void UdpPublish(string _json)
        {
            try
            {
                if (!this.IsUdpPublish)
                {
                    return;
                }
                var th = new Thread((ob) =>
                {
                    try
                    {
                        var json = (string)ob;
                        UdpHelper.Send(json, this.UdpPort);
                        try
                        {
                            if (this.IsUdpPublishLog)
                            {
                                var sLog = $@"
【描述】= 数据推手(UDP)数据统一推送
【端口】= {this.UdpPort}
【数据】=
{Tool.ConvertJsonString(json)}
";
                                LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Deal UdpPublish 133Err:{ex.Message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Deal UdpPublish 0Err:{ex.Message}");
                    }
                });
                th.Start(_json);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Deal UdpPublish Err:{ex.Message}");
            }
        }

    }
}
